package com.xja.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xja.mapper.EvaluationMapper;
import com.xja.mapper.TongueMapper;
import com.xja.model.dto.EvaluationDTO;
import com.xja.model.dto.QuestionDTO;
import com.xja.model.dto.TongueDescriptionDTO;
import com.xja.model.entity.Evaluation;
import com.xja.model.entity.Tongue;
import com.xja.service.IEvaluationService;
import com.xja.service.ITongueService;
import com.xja.utils.ChatClientHolder;
import com.xja.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评测表 服务实现类
 * </p>
 *
 * @author caijg
 * @since 2025-06-08
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class EvaluationServiceImpl extends ServiceImpl<EvaluationMapper, Evaluation> implements IEvaluationService {

    private final ITongueService tongueService;
    private final ChatClientHolder chatClientHolder;
    private final TongueMapper tongueMapper;
    @Override
    public Evaluation getResult(EvaluationDTO evaluationDTO) {
        // 1.拿到舌苔的五个特征描述
        Long uid = UserContext.getUid();
        //evaluationDTO.setTongueDiagnosisId(tongueService.diagnosis());
        Tongue tongue = null;
        if(evaluationDTO.getTongueDiagnosisId()!=null){
            tongue = tongueService.getById(evaluationDTO.getTongueDiagnosisId());
        }else {
            QueryWrapper<Tongue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", uid);
            queryWrapper.orderByDesc("create_time");
            List<Tongue> tongues = tongueMapper.selectList(queryWrapper);
            tongue = tongues.get(0);
        }
        TongueDescriptionDTO tongueDescriptionDTO = BeanUtil.toBean(tongue, TongueDescriptionDTO.class);

        // 2.发送给Qwen大模型进行分析，拿到JSON
        Evaluation evaluation = getLLModelResult(tongueDescriptionDTO, evaluationDTO.getAnswers());
        log.info("评测结果:{}", evaluation);

        // 3.存储测评结果到数据库
        evaluation.setId(null);
        evaluation.setCreateTime(LocalDateTime.now());
        evaluation.setUserId(UserContext.getUid());
        evaluation.setTongueDiagnosisId(tongue.getId());
        this.save(evaluation);

        // 4.返回结果
        return evaluation;
    }

    private Evaluation getLLModelResult(TongueDescriptionDTO tongueDescriptionDTO, ArrayList<QuestionDTO> answers) {
        // 获取评测大模型
        ChatClient evaluateChatClient = chatClientHolder.getEvaluateChatClient();
        // 构造提示词
        String userText = """
              身体情况问卷：{questions}
              "舌诊报告": {tongue}
              """;
        PromptTemplate promptTemplate = new PromptTemplate(userText);
        Message message = promptTemplate.createMessage(Map.of("tongue", tongueDescriptionDTO.toString()
                , "questions", answers));

        // 返回生成的测评结果
        return evaluateChatClient.prompt()
                .messages(message)
                .call()
                .entity(Evaluation.class);
    }

    /**
     * 获取历史评估记录
     */
    @Override
    public List<Evaluation> getHistory() {
        // 1.获取当前用户id
        Long userId = UserContext.getUid();

        // 2.查询数据库，获取当前用户的历史评测结果
        return this.query()
                .eq("user_id", userId)
                .orderByDesc("create_time")
                .list();
    }

    /**
     * 删除测评历史记录
     * @param ids 需要删除的历史评测结果的id
     */
    @Override
    public Boolean deleteHistory(ArrayList<String> ids) {
        return this.removeByIds(ids);
    }
}